package com.slipper.gen;

import com.slipper.gen.dao.GeneratorDao;
import com.slipper.gen.util.GenUtil;
import org.apache.commons.io.IOUtils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;

public class GenMain {
    public static void main(String[] args) throws Exception {
        GeneratorDao dao = createDao();
        String[] tableNames = {
                "t_stock_deal",
        };

        File desktopDir = FileSystemView.getFileSystemView().getHomeDirectory();
        String desktopPath = desktopDir.getAbsolutePath();
        File file = new File(desktopDir + "/tables.zip");
        FileOutputStream outputStream = new FileOutputStream(file);
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        for (String tableName : tableNames) {
            Map<String, String> table = dao.queryTable(tableName);
            List<Map<String, Object>> columns = dao.queryColumns(tableName);
            GenUtil.generatorCode(table, "t_", columns, zip);
        }
        IOUtils.closeQuietly(zip);
        outputStream.flush();

        System.out.println();
        System.out.println("代码保存目录：file:///" + desktopPath.replaceAll("\\\\", "/"));
        System.out.println("代码保存路径：file:///" + file.getAbsolutePath().replaceAll("\\\\", "/"));
    }

    private static GeneratorDao createDao() throws IOException {
        String resource = "mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(reader);
        SqlSession sqlSession = ssf.openSession();
        return sqlSession.getMapper(GeneratorDao.class);
    }
}
